package com.book.service.impl;

import com.book.pojo.Comment;
import com.book.mapper.CommentDao;
import com.book.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cxy
 * @since 2023-10-12 17:15:29
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentDao, Comment> implements CommentService {

    @Autowired
    private CommentDao commentDao;


    @Override
    public List<Comment> selectAuthorComment(Long authorId) {
        return commentDao.selectAuthorComment(authorId);
    }

    @Override
    public List<Map<String, Object>> selectCommentByBookIdZtree(Long bookId) {
        List<Comment> commentList = commentDao. selectCommentByBookId(bookId);
        List<Map<String, Object>> list =getAllZtree(0,commentList);
        return list;
    }
    private List<Map<String, Object>> getAllZtree(int pid, List<Comment> commentList) {
        List<Map<String, Object>> list =new ArrayList<>();
        for (Comment comment : commentList) {
            if (comment.getPid()==pid){
                Map<String,Object> map = new HashMap<>();
                map.put("id",comment.getId());
                map.put("name",comment.getContent());
                map.put("children",getAllZtree(Math.toIntExact(comment.getId()),commentList));
                if (getAllZtree(Math.toIntExact(comment.getId()),commentList).size()==0){
                    map.remove("children");
                }
                list.add(map);
            }
        }
        return list;
    }

    @Override
    public void addComment(Comment comment) {
        commentDao.insert(comment);
    }

    @Override
    public void deleteComment(Long id) {
        //根据id查询全部
        Comment comment = commentDao.selectById(id);
        //找到对应bookid
        Long bookId = comment.getBookId();
        List<Comment> commentList = commentDao. selectCommentByBookId(bookId);
        deleteCommentZtree(id,commentList);
        commentDao.deleteById(id);

    }
    //删除的递归
    public void deleteCommentZtree(Long id, List<Comment> commentList) {
        for (Comment comment : commentList) {
            if (comment.getPid()==id){
                commentDao.deleteById(id);
                deleteCommentZtree(comment.getId(),commentList);
            }
        }
    }

    @Override
    public void updateLike(Comment comment) {
        commentDao.updateById(comment);
    }
}

